#pragma once

#include <iostream>
#include <string>
#include <functional>

#include "Inetaddr.hpp"

// 将所有的文件的传递都视为链接，包括listensocket
class myConnection;
class Reactor;
using handler_t = std::function<void (myConnection *con)>;

#define ListenConnection 0
#define NormalConnection 1

class myConnection
{
public:
    myConnection(int socketfd)
        :_socketfd(socketfd)
    {

    }

    // ③
    void registerHandler(handler_t recver, handler_t sender, handler_t excepter)
    {
        _handler_recver = recver;
        _handler_sender = sender;
        _handler_excepter = excepter;
    }

    void setEvents(uint32_t events)
    {
        _events = events;
    }

    uint32_t getEvents()
    {
        return _events;
    }
    
    int getsocketfd()
    {
        return _socketfd;
    }

    void setReactor(Reactor *R)
    {
        _R = R;
    }

    void setConnectionType(int type)
    {
        _type = type;
    }

    int getConnectionType()
    {
        return _type;
    }

    void setAddr(const inetAddr &addr)
    {
        _addr = addr;
    }

    void appendInBuffer(const std::string &in)
    {
        _inbuffer += in;
    }

    void appendOutBuffer(const std::string &out)
    {
        _outbuffer += out;
    }

    std::string& getinBuffer()
    {
        return _inbuffer;
    }

    std::string& getoutBuffer()
    {
        return _outbuffer;
    }

    void DiscardoutBuffer(int n)
    {
        _outbuffer.erase(0, n);
    }

    void close()
    {
        if (_socketfd >= 0)
        {
            ::close(_socketfd);
        }
        
    }

    ~myConnection()
    {

    }
private:
    int _socketfd;
    uint32_t _events;

    std::string _inbuffer; // 表示
    std::string _outbuffer;
    int _type;

// 可以改成private限定 + get方法
public:
    handler_t _handler_recver;  //处理读取
    handler_t _handler_sender;  //处理写入
    handler_t _handler_excepter;//处理异常

    Reactor *_R; // Connection对象中的 _R 成员可以指向这个连接所属的 Reactor类型的对象
    inetAddr _addr;
};
